//
//  SNOrganizationViewController.m
//  ZhuoxinAgriculture
//
//  Created by stone on 16/12/16.
//  Copyright © 2016年 stone. All rights reserved.
//

#import "MJRefresh.h"
#import "SNRetailInvestorViewController.h"
#import "SNFarmViewController.h"
#import "SNArtelViewController.h"
#import "SNOrganizationModel.h"
#import "SNOrganizationViewController.h"
#import "SNOrganizationCell.h"
#import "SNSearchView.h"
#import "SiftView.h"

#define kPageSize @"15"
static BOOL __needUPDate = NO;
static NSString * __fullName = nil;
@interface SNOrganizationViewController ()<UITableViewDataSource,UITableViewDelegate>
/** orgtypeStrM */
@property (nonatomic,copy) NSString * orgtypeStrM;
/** searchBackgroundView */
@property (weak, nonatomic) SNSearchView * searchView;
/** tableView */
@property (nonatomic,weak) UITableView * tableView;

@property (nonatomic, strong) NSMutableArray<SNOrganizationResult *> *organizationModels;

/** selectedIndexs */
@property (nonatomic,strong) NSMutableArray<NSNumber *> * selectedIndexs;
/**
 *  当前页数
 */
@property (nonatomic, assign) NSInteger currentPage;
/**
 *  总页数
 */
@property (nonatomic, assign) NSInteger totalPage;

@end

@implementation SNOrganizationViewController
-(NSString *)orgtypeStrM{
    if (_orgtypeStrM.length > 0) {
        return _orgtypeStrM;
    }else{
        return @"[1,2,3]";
    }
    
}
+ (BOOL)getNeedUPDate{
    return __needUPDate;
}
+ (void)setNeedUPDate:(BOOL)needUPDate{
    __needUPDate = needUPDate;
}
+ (NSString *)getFullName{
    return __fullName;
}
+ (void)setFullName:(NSString *)fullName{
    __fullName = fullName;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    if (__needUPDate == YES) {
        //更新
        [self fooWithUserId:kUserInfo.userId orgtype:self.orgtypeStrM fullName:__fullName currentPage:@"1" pageSize:kPageSize];
        self.searchView.textField.text = __fullName;
    }
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    __needUPDate = NO;
    __fullName = nil;
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.title = @"组织列表";
    // Do any additional setup after loading the view.
    [self addSearchView];
    [self addTableView];
    // [self addRequest];
}

- (void)fooWithUserId:(NSString *)userId orgtype:(NSString *)orgtype fullName:(NSString *)fullName currentPage:(NSString *)currentPage pageSize:(NSString *)pageSize
{
    MBProgressHUD * hud = [SNProgressManager showToView:self.view title:@"加载中"];
    [[ZXHTTPManager sharedManager] viewOrgInfoWithUserId:userId orgtype:orgtype fullName:fullName currentPage:currentPage pageSize:pageSize completed:^(NSDictionary *jsonDict, NSError *error) {
        
        [hud hideAnimated:YES];
        if (error) {
            NSLog(@"error = %@",error);
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
            return;
        }

        
        //NSLog(@"%@",jsonDict);
        
        SNOrganizationModel * organizationModel = [SNOrganizationModel mj_objectWithKeyValues:jsonDict];
        if(organizationModel.status.integerValue == 0){
            //成功
            
            self.organizationModels = organizationModel.result.mutableCopy;
            self.currentPage = organizationModel.currentPage.integerValue;
            self.totalPage = organizationModel.totalPage.integerValue;
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        }else{
            [SNProgressManager showToView:self.view toast:organizationModel.message afterDelay:2];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        }
    }];
}
- (NSMutableString *)filterData:(NSArray<SNSiftButton *> *)buttons
{
    self.selectedIndexs = [NSMutableArray array];
    NSMutableString * strM = @"[".mutableCopy;
    
    for(int i = 0; i < buttons.count; i++) {
        SNSiftButton * siftButton = buttons[i];
        
        if (siftButton.selected) {
            [strM appendFormat:@"%d,",i+1];
            [self.selectedIndexs addObject:@(i)];
        }
    }
    
    NSRange range = [strM rangeOfString:@"," options:NSBackwardsSearch];
    
    if (range.location != NSNotFound) {
        [strM deleteCharactersInRange:range];
        [strM appendString:@"]"];
    }else{
        [strM appendString:@"1,2,3]"];
    }
    return strM;
}
- (void)addSearchView
{
    SNSearchView * searchView = ({
        SNSearchView * view = [[SNSearchView alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 46) tapEnable:NO];
        view.nav = self.navigationController;
        @weakify_self
        [view setSiftBlock:^{
            @strongify_self
            /** 蒙版 */
            UIView * bgView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
            bgView.backgroundColor = [UIColor blackColor];
            bgView.alpha = 0.0;
            [self.navigationController.view addSubview:bgView];
            //sn_note:=========  ============================ stone 🐳 ===========/
            
            SiftView * siftView =  [SiftView view];
            siftView.bgView = bgView;
            
            if (self.selectedIndexs.count > 0) {
                siftView.selectedIndexs = self.selectedIndexs;
            }
            
            @weakify_self
            [siftView setDownButtonClickedBlock:^(NSArray<SNSiftButton *> * buttons) {
                @strongify_self
                //  @"['1','2','3']"
                NSMutableString * strM = [self filterData:buttons];
                self.orgtypeStrM = strM;
                [self fooWithUserId:kUserInfo.userId orgtype:strM fullName:__fullName currentPage:@"1" pageSize:kPageSize];
            }];
            
            CGFloat w = 338 / 375.0 * [UIScreen mainScreen].bounds.size.width;
            siftView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width, 0, w, [UIScreen mainScreen].bounds.size.height);
            
            [self.navigationController.view addSubview:siftView];
            
            [UIView animateWithDuration:0.5 delay:0 options:UIViewAnimationOptionCurveEaseInOut animations:^{
                bgView.alpha = 0.7;
                //
                CGFloat w = 338 / 375.0 * [UIScreen mainScreen].bounds.size.width;
                siftView.frame = CGRectMake([UIScreen mainScreen].bounds.size.width - w, 0, w, [UIScreen mainScreen].bounds.size.height);
            } completion:^(BOOL finished) {
                //
            }];
        }];
        
        [self.view addSubview:view];
        
        view;
    });
    self.searchView = searchView;
    
    
//    CGSize size = searchView.textField.bounds.size;
//    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
//    
//    CGContextRef context = UIGraphicsGetCurrentContext();
//    
//    [searchView.textField.layer renderInContext:context];
//    
//    UIImage * newImage = UIGraphicsGetImageFromCurrentImageContext();
//    
//    //	UIImageWriteToSavedPhotosAlbum(newImage, NULL, NULL, NULL);
//    NSData * data =   UIImagePNGRepresentation(newImage);
//    
//    [data writeToFile:@"/Users/stone/Desktop/aa.png" atomically:YES];
//    
//    UIGraphicsEndImageContext();
}
- (void)addTableView
{
    CGRect frame = CGRectMake(0, CGRectGetMaxY(self.searchView.frame), self.view.bounds.size.width, self.view.bounds.size.height - CGRectGetMaxY(self.searchView.frame));
    UITableView * tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStyleGrouped];
    self.tableView = tableView;
    [self setupInit:tableView];
    
    [self.view addSubview:tableView];
    
    [self addObserver];
    [self addRequest];
}
#pragma mark - <addRequest>
- (void)addRequest {
    // addRequest

    //    [self fooWithUserId:kUserInfo.userId orgtype:@"[1,2,3]" fullName:nil currentPage:@"1" pageSize:kPageSize];
    MBProgressHUD * hud = [SNProgressManager showToView:self.view title:@"加载中"];
    [[ZXHTTPManager sharedManager] viewOrgInfoWithUserId:kUserInfo.userId orgtype:self.orgtypeStrM fullName:__fullName currentPage:@"1" pageSize:kPageSize completed:^(NSDictionary *jsonDict, NSError *error) {
        
        [hud hideAnimated:YES];
        if (error) {
            NSLog(@"error = %@",error);
            
            return;
        }
        
        
        //NSLog(@"%@",jsonDict);
        
        SNOrganizationModel * organizationModel = [SNOrganizationModel mj_objectWithKeyValues:jsonDict];
        if(organizationModel.status.integerValue == 0){
            //成功
            
            self.organizationModels = organizationModel.result.mutableCopy;
            self.currentPage = organizationModel.currentPage.integerValue;
            self.totalPage = organizationModel.totalPage.integerValue;
            [self.tableView reloadData];
        }else{
            [SNProgressManager showToView:self.view toast:organizationModel.message afterDelay:2];
        }
    }];
}
#pragma mark - <addObserver>
- (void)addObserver {
    // addObserver
}
- (void)dealloc {
    NSLog(@"%@ %s %@",[self class], __func__ , @"im dying");
    __fullName = nil;
    __needUPDate = NO;
}

- (void)setupInit:(UITableView *)tableView {
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = [UIColor whiteColor];
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    UIView *footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 12)];
    tableView.tableFooterView = footerView;
    
    [self setHeights:tableView];
    [self registerNib:tableView];
    [self registerClass:tableView];
    [self addHeaderFooterRefresh:tableView];
}
- (void)addHeaderFooterRefresh:(UITableView *)tableView {
    
    tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestNew)];
    /** view创建 就刷新 , 不想用... */
    //    [tableView.gb_header beginRefreshing];
    
    tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(requestMore)];
}
- (void)requestNew {
    
    self.currentPage = 1;
    self.totalPage = 0;
    
    
//    [self fooWithUserId:kUserInfo.userId orgtype:@"[1,2,3]" fullName:nil currentPage:@"1" pageSize:kPageSize];
    
//    MBProgressHUD * hud = [SNProgressManager showToView:self.view title:@"加载中"];
    [[ZXHTTPManager sharedManager] viewOrgInfoWithUserId:kUserInfo.userId orgtype:self.orgtypeStrM fullName:__fullName currentPage:@"1" pageSize:kPageSize completed:^(NSDictionary *jsonDict, NSError *error) {
        
//        [hud hideAnimated:YES];
        if (error) {
            NSLog(@"error = %@",error);
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
            return;
        }
        
        
        //NSLog(@"%@",jsonDict);
        
        SNOrganizationModel * organizationModel = [SNOrganizationModel mj_objectWithKeyValues:jsonDict];
        if(organizationModel.status.integerValue == 0){
            //成功
            
            self.organizationModels = organizationModel.result.mutableCopy;
            
            self.currentPage = organizationModel.currentPage.integerValue;
            self.totalPage = organizationModel.totalPage.integerValue;
            
            [self.tableView reloadData];
            
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        }else{
            [SNProgressManager showToView:self.view toast:organizationModel.message afterDelay:2];
            [self.tableView.mj_header endRefreshing];
            [self.tableView.mj_footer resetNoMoreData];
        }
    }];

    
    
    
//    [[ZXHTTPManager sharedManager] viewruleplanWithUserId:kUserInfo.userId year:[self getYear] currentPage:@"1" pageSize:kPageSize custName:nil completed:^(NSDictionary *jsonDict, NSError *error) {
//        
//        if (error) {
//            NSLog(@"error = %@",error);
//            [self.tableView.mj_header endRefreshing];
//            [self.tableView.mj_footer resetNoMoreData];
//            return;
//        }
//        
//        //NSLog(@"%@",jsonDict);
//        
//        SNPlantingDecisionMakerModel * plantingDecisionMakerModel = [SNPlantingDecisionMakerModel mj_objectWithKeyValues:jsonDict];
//        
//        self.currentPage = plantingDecisionMakerModel.currentPage.integerValue;
//        self.totalPage = plantingDecisionMakerModel.totalPage.integerValue;
//        
//        self.plantingDecisionMakerModel = plantingDecisionMakerModel;
//        
//        [self.tableView reloadData];
//        
//        [self.tableView.mj_header endRefreshing];
//        [self.tableView.mj_footer resetNoMoreData];
//    }];
    
    
}
- (void)requestMore {
    
    if (self.currentPage < self.totalPage) {
        self.currentPage++;
        
        [[ZXHTTPManager sharedManager] viewOrgInfoWithUserId:kUserInfo.userId orgtype:self.orgtypeStrM fullName:__fullName currentPage:[NSString stringWithFormat:@"%ld",self.currentPage] pageSize:kPageSize completed:^(NSDictionary *jsonDict, NSError *error) {
            
            if (error) {
                NSLog(@"error = %@",error);
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer resetNoMoreData];
                return;
            }
            
            
            //NSLog(@"%@",jsonDict);
            
            SNOrganizationModel * organizationModel = [SNOrganizationModel mj_objectWithKeyValues:jsonDict];
            if(organizationModel.status.integerValue == 0){
                //成功
                
                //  NSMutableArray<SNOrganizationResult *> * arrM = organizationModel.result.mutableCopy;
                
                //  self.organizationModels = organizationModel.result.mutableCopy;
                
                NSArray * array =  [self.organizationModels arrayByAddingObjectsFromArray:organizationModel.result];
                self.organizationModels = array.mutableCopy;
                
                self.currentPage = organizationModel.currentPage.integerValue;
                self.totalPage = organizationModel.totalPage.integerValue;
                
                [self.tableView reloadData];
                
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer resetNoMoreData];
            }else{
                [SNProgressManager showToView:self.view toast:organizationModel.message afterDelay:2];
                [self.tableView.mj_header endRefreshing];
                [self.tableView.mj_footer resetNoMoreData];
            }
        }];
        
//sn_note:=========  ============================ stone 🐳 ===========/
        
        
//        [[ZXHTTPManager sharedManager] viewruleplanWithUserId:kUserInfo.userId year:[self getYear] currentPage:[NSString stringWithFormat:@"%ld",self.currentPage] pageSize:kPageSize custName:nil completed:^(NSDictionary *jsonDict, NSError *error) {
//            
//            if (error) {
//                NSLog(@"error = %@",error);
//                [self.tableView.mj_header endRefreshing];
//                [self.tableView.mj_footer resetNoMoreData];
//                return;
//            }
//            
//            //NSLog(@"%@",jsonDict);
//            
//            SNPlantingDecisionMakerModel * plantingDecisionMakerModel = [SNPlantingDecisionMakerModel mj_objectWithKeyValues:jsonDict];
//            
//            self.currentPage = plantingDecisionMakerModel.currentPage.integerValue;
//            self.totalPage = plantingDecisionMakerModel.totalPage.integerValue;
//            
//            NSArray * array =  [self.plantingDecisionMakerModel.result arrayByAddingObjectsFromArray:plantingDecisionMakerModel.result];
//            self.plantingDecisionMakerModel.result = array;
//            [self.tableView reloadData];
//            
//            [self.tableView.mj_header endRefreshing];
//            [self.tableView.mj_footer resetNoMoreData];
//        }];
        
    } else {
        
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    }
}
#pragma mark - <Register>
/** registerNib */
- (void)registerNib:(UITableView *)tableView {
        [tableView registerNib:[UINib nibWithNibName:NSStringFromClass([SNOrganizationCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([SNOrganizationCell class])];
}
/** registerClass */
- (void)registerClass:(UITableView *)tableView {
    //    [tableView registerClass:[SNTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SNTableViewCell class])];
    [tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:NSStringFromClass([UITableViewCell class])];
    //    [tableView registerClass:[UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:NSStringFromClass([UITableViewHeaderFooterView class])];
}
#pragma mark - <SetHeights>
/** setHeights */
- (void)setHeights:(UITableView *)tableView {
    
    /** header */
    tableView.sectionHeaderHeight = 12;
    // tableView.estimatedSectionHeaderHeight = 100;
    // tableView.sectionHeaderHeight = UITableViewAutomaticDimension;
    /** cell */
    tableView.estimatedRowHeight = 120;
    tableView.rowHeight = UITableViewAutomaticDimension;
    /** footer */
    tableView.sectionFooterHeight = 0.001;
    // tableView.estimatedSectionFooterHeight = 100;
    // tableView.sectionFooterHeight = UITableViewAutomaticDimension;
}

#pragma mark - <UITableViewDataSource>
/** 组数 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.organizationModels.count;
}
/** 行数 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
//MARK: -
//MARK: - cell
/** cell */
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    SNOrganizationCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SNOrganizationCell class])];
    //    SNTableViewCell * cell = [SNTableViewCell cellWithTableView:tableView];
    
    cell.model = self.organizationModels[indexPath.section];
    
//    cell.contentView.backgroundColor = indexPath.row % 2 == 0 ? [UIColor colorWithRed:247 / 255.0 green:206 / 255.0 blue:166 / 255.0 alpha:1.0] : [UIColor colorWithRed:242 / 255.0 green:154 / 255.0 blue:76 / 255.0 alpha:1.0];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    return cell;
}
#pragma mark - <UITableViewDelegate>
/** 自定义section header */
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UITableViewHeaderFooterView * headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:NSStringFromClass([UITableViewHeaderFooterView class])];
    
    //    SNHeaderView * headerView = [SNHeaderView headerViewWithTableView:tableView];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 0.001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 12;
}
/** 选中一行 */
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%s", __func__);
    
    SNOrganizationResult *model = self.organizationModels[indexPath.section];
    
    switch (model.organType.integerValue) {
        case 1://合作社
        {
            SNArtelViewController * vc = [[SNArtelViewController alloc] init];
            vc.custinfolist = model.custinfoList;
            vc.SHORTNAME = ([model.fullName isEqualToString:@""] || model.fullName == nil)?@"未知":model.fullName;
            vc.iconImageName = @"合作社头像";
            vc.MEMBERQTY = model.memberqty;
            vc.COMPANYNO = model.companyNo;
            [self.navigationController pushViewController:vc animated:YES];
        }
            
            break;
        case 2://农场
        {
//            SNFarmViewController * vc = [SNFarmViewController new];
//            vc.model = model;
//            [self.navigationController pushViewController:vc animated:YES];
            SNArtelViewController * vc = [[SNArtelViewController alloc] init];
            vc.custinfolist = model.custinfoList;
            vc.SHORTNAME = ([model.fullName isEqualToString:@""] || model.fullName == nil)?@"未知":model.fullName;
            vc.iconImageName = @"农场";
            vc.MEMBERQTY = model.memberqty;
            vc.COMPANYNO = model.companyNo;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 3://大户
        {
//            SNRetailInvestorViewController * vc = [SNRetailInvestorViewController new];
//            vc.model = model;
//            [self.navigationController pushViewController:vc animated:YES];
            SNArtelViewController * vc = [[SNArtelViewController alloc] init];
            vc.custinfolist = model.custinfoList;
            vc.SHORTNAME = ([model.fullName isEqualToString:@""] || model.fullName == nil)?@"未知":model.fullName;
            vc.iconImageName = @"大户";
            vc.MEMBERQTY = model.memberqty;
            vc.COMPANYNO = model.companyNo;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        default:
            break;
    }
    
}
/** 取消 选中 */
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath NS_AVAILABLE_IOS(3_0) {
    NSLog(@"%s", __func__);
}
/** 可编辑 */
//- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return YES;
//}
/** 删除样式 */
//- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    return UITableViewCellEditingStyleDelete;
//}
/** 删除当前行 */
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//
//        [self.models removeObjectAtIndex:indexPath.row];
//
//        [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationLeft];
//}
@end
